<?php
declare (strict_types=1);

namespace app\api\controller\master;

use app\Api\model\GroupMaster;
use app\api\model\GroupMasterAddress;
use app\api\model\Users;
use app\serve\controller\Token;
use think\facade\Db;
use think\facade\Validate;
use think\Request;

class ApplyFor
{
    public function applyForGroupMaster(Request $request)
    {
        //接收参数
        $params = input();
        //参数验证
        $validate = Validate::rule([
            'true_name|姓名' => 'require|min:2|max:10',
            'mobile|手机号' => 'require|mobile|unique:group_master',
            'id_card|身份证号码' => 'require|idCard|unique:group_master',
            'longitude|所在地' => 'require',
            'latitude|所在地' => 'require',
            'plot|小区' => 'require',
            'detailed_address|详细地址' => 'require'
        ], $params);
        //验证不通过 返回提示信息
        if (!$validate->check($params)) {
            return json(['code' => 10004, 'msg' => $validate->getError(), 'data' => []]);
        }
        $token = $request->header('token');
        $res = (new Token())->chekToken($token);
        if ($res['code'] != 1) {
            return json(['error_code' => 10002, 'msg' => $res['msg'], 'data' => ''], 400);
        }
        $user_id = $res['data']->user_id;
        //拼接团长基本信息数据
        $data = [
            'user_id' => $user_id,
            'true_name' => $params['true_name'],
            'id_card' => $params['id_card'],
            'mobile' => $params['mobile'],
            'register_time' => time(),
            'audit_time' => time()
        ];
        Db::startTrans();
        try {
            //实例化模型 进行添加操作
            $group_master_model = new GroupMaster();
            //获取团长id
            $master_id = $group_master_model->addGroupMaster($data);
            $master_address_model = new GroupMasterAddress();
            //组装团长地址信息
            $address = [
                'master_id' => $master_id,
                'longitude' => $params['longitude'],
                'latitude' => $params['latitude'],
                'plot' => $params['plot'],
                'detailed_address' => $params['detailed_address']
            ];
            //添加团长地址
            $address_res = $master_address_model->addAddress($address);
            if (!$address_res){
                Db::rollback();
                return json(['code'=>10003,'msg'=>'申请提交失败,请仔细检查输入的内容','data'=>[]]);
            }
            Db::commit();
            return json(['code'=>10001,'msg'=>'申请已提交,管理员会在24小时内告知您审核结果','data'=>[]]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>10003,'msg'=>'申请提交失败,请联系管理员','data'=>[]]);
        }
    }
}
